#!/usr/bin/env ruby
require 'csv'

# Examples of toplev.csv output.
# Timestamp,CPUs,Area,Value,Unit,Description,Sample,Stddev,Multiplex,Bottleneck
# 0.131583491,S0-C0,Frontend_Bound,22.79,% Slots,,frontend_retired.latency_ge_8:pp,0.00,6.9,
# 0.131583491,S0-C0,Bad_Speculation,39.50,% Slots,,,0.00,6.84,
# 0.131583491,S0-C0,Backend_Bound,10.65,% Slots,,,0.00,6.84,
# 0.131583491,S0-C0,Frontend_Bound.Frontend_Bandwidth,22.77,% Slots,,frontend_retired.latency_ge_2_bubbles_ge_1:pp,0.00,6.9,
# 0.131583491,S0-C0,Bad_Speculation.Branch_Mispredicts,39.84,% Slots,,br_misp_retired.all_branches,0.00,6.9,<==
# 0.131583491,S0-C0-T0,MUX,6.84,%,,,0.00,100.0,
# 0.131583491,S0-C1,Backend_Bound,56.52,% Slots,,,0.00,6.84,
# ...
# 9.829300247,S1-C28-T1,MUX,7.03,%,,,0.00,100.0,
# 9.829300247,S1-C29-T1,MUX,7.03,%,,,0.00,100.0,
# # 4.0-full on Intel(R) Xeon(R) Gold 6252 CPU @ 2.10GHz

RESULT_ROOT = ENV['RESULT_ROOT']
exit unless File.exist?("#{RESULT_ROOT}/toplev.csv")
toplev_csv = "#{RESULT_ROOT}/toplev.csv"

last_time = ''
bottleneck_value = 0
CSV.foreach(toplev_csv) do |row|
  next if row[0] =~ /^#/ || row[0] =~ /^Timestamp/

  # row = ["8.048139281", "S0-C0", "Frontend_Bound",
  #        "69.86", "% Slots", nil, nil, "0.00", "0.0", "<=="]
  time = row.shift
  puts "time: #{time}" if time != last_time
  last_time = time
  key_arr = []
  row.each do |item|
    case item
    when /\d+\.\d+/
      bottleneck_value = item
      break
    else
      key_arr.push item
    end
  end
  key = key_arr.join('.')
  puts "#{key}: #{bottleneck_value}"
end
